import axios from "axios";
import router from "../router";
// import $store from "../store";
// import toLogin from "../libs/login";
// import { VUE_APP_API_URL } from "../utils/index";

import {
    getToken,
    setToken
} from '@/utils/auth'
import query from './query'
const instance = axios.create({
    baseURL: process.env.VUE_APP_BASE_API + process.env.VUE_APP_PREFIX_API,
    timeout: 50000
});
const defaultOpt = {
    login: true
};


instance.interceptors.request.use(config => {
    if (config.url.indexOf('login') == -1) {
        const token = getToken()
        if (token) {
            const headers = config.headers || {};
            headers["Authorization"] = "Bearer " + token;
            config.headers = headers;
        }
    }


    let review_guid = query.getUrlKey('review_guid')
    if (review_guid) {
        const headers = config.headers || {};
        headers["review_guid"] = review_guid;
        config.headers = headers;
    }
    if (config.url.indexOf('file') == -1) {
        const headers = config.headers || {};
        headers["Content-Type"] = 'application/json; charset=utf-8';
        config.headers = headers;
    } else {
        const headers = config.headers || {};
        headers["Content-Type"] = 'application/x-www-form-urlencoded';
        config.headers = headers;
    }
    return config
})
instance.interceptors.response.use(res => {
    if (res.data.code == -403) {
        localStorage.setItem('token', null)
        location.href = process.env.VUE_APP_API_URL + process.env.VUE_API_PREFIXY + '/mpoauth2/oauth'
    }
    return res
})

function baseRequest(options) {
    return instance(options).then(res => {
        const data = res.data || {};
        if (!data) {
            return Promise.reject({
                msg: "请求失败",
                res,
                data
            })
        } else {
            return Promise.resolve(data, res);
        }
    });
}

/**
 * http 请求基础类
 * 参考文档 https://www.kancloud.cn/yunye/axios/234845
 *
 */
const request = ["post", "put", "patch"].reduce((request, method) => {
    /**
     *
     * @param url string 接口地址
     * @param data object get参数
     * @param options object axios 配置项
     * @returns {AxiosPromise}
     */
    request[method] = (url, data = {}, options = {}) => {
        return baseRequest(
            Object.assign({
                url,
                data,
                method
            }, defaultOpt, options)
        );
    };
    return request;
}, {});

["get", "delete", "head"].forEach(method => {
    /**
     *
     * @param url string 接口地址
     * @param params object get参数
     * @param options object axios 配置项
     * @returns {AxiosPromise}
     */
    request[method] = (url, params = {}, options = {}) => {
        return baseRequest(
            Object.assign({
                url,
                params,
                method
            }, defaultOpt, options)
        );
    };
});

export default request;